package com.jessehu.dataquery;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.jessehu.dataquery.adapter.QueryResultAdapter;
import com.jessehu.dataquery.dbtable.Person;
import com.jessehu.dataquery.dbtable.Student;
import com.jessehu.dataquery.dbtable.Teacher;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * MainActivity
 *
 * @author JesseHu
 * @date 2018/12/20
 */
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.et_age)
    EditText ageInput;
    @BindView(R.id.lv_query_result)
    ListView queryResultView;

    private String[] mTeacherNames = {"Jack", "Tom", "Sam"};

    private static final int STUDENT_COUNT = 25;
    private static final int MAX_AGE_STUDENT = 15;
    private static final int MIN_AGE_STUDENT = 11;
    private static final int MAX_AGE_TEACHER = 52;
    private static final int MIN_AGE_TEACHER = 25;

    private List<Student> mJackStudents;
    private List<Student> mTomStudents;
    private List<Student> mSamStudents;
    private List<Person> mQueryResult;
    private QueryResultAdapter mResultAdapter;
    private Random mRandom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mJackStudents = new ArrayList<>();
        mTomStudents = new ArrayList<>();
        mSamStudents = new ArrayList<>();
        mQueryResult = new ArrayList<>();
        mRandom = new Random();
        initData();

        // 初始化的时候加载一个空的List
        mResultAdapter = new QueryResultAdapter(this, mQueryResult);
        queryResultView.setAdapter(mResultAdapter);
    }

    /**
     * 创建数据
     */
    private void initData() {
        List<Student> students = LitePal.findAll(Student.class);
        List<Teacher> teachers = LitePal.findAll(Teacher.class);

        // 如果数据已存在则不进行重复创建
        if (students == null || students.size() == 0) {
            // 创建学生数据
            for (int i = 0; i < STUDENT_COUNT; i++) {
                String studentName = String.format(Locale.getDefault(), "Student%02d", i + 1);
                int studentAge = mRandom.nextInt(MAX_AGE_STUDENT - MIN_AGE_STUDENT + 1) + MIN_AGE_STUDENT;
                // sex 0==F 1==M
                int studentSex = mRandom.nextInt(2);

                Student student = new Student();
                student.setName(studentName);
                student.setAge(studentAge);
                student.setSex(studentSex);
                student.save();

                if (0 == i % 3) {
                    mJackStudents.add(student);
                } else if (1 == i % 3) {
                    mTomStudents.add(student);
                } else {
                    mSamStudents.add(student);
                }
            }
        }

        if (teachers == null || teachers.size() == 0) {
            // 创建教师数据
            for (int i = 0; i < mTeacherNames.length; i++) {
                int teacherAge = mRandom.nextInt(MAX_AGE_TEACHER - MIN_AGE_TEACHER + 1) + MIN_AGE_TEACHER;
                int teacherSex = mRandom.nextInt(2);

                Teacher teacher = new Teacher();
                teacher.setName(mTeacherNames[i]);
                teacher.setAge(teacherAge);
                teacher.setSex(teacherSex);

                if (0 == i) {
                    teacher.setStudents(mJackStudents);
                } else if (1 == i) {
                    teacher.setStudents(mTomStudents);
                } else {
                    teacher.setStudents(mSamStudents);
                }

                teacher.save();
            }
        }
    }

    /**
     * 按年龄搜索
     *
     * @param view
     */
    @OnClick(R.id.btn_query_age)
    public void queryByAge(View view) {
        String age = ageInput.getText().toString().trim();
        if (TextUtils.isEmpty(age)) {
            Toast.makeText(this, "年龄不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        List<Student> students = LitePal.where("age like ?", age).find(Student.class);
        refreshView(students);
    }

    /**
     * 搜索所有的学生
     *
     * @param view
     */
    @OnClick(R.id.btn_query_all_students)
    public void queryAllStudent(View view) {
        List<Student> students = LitePal.findAll(Student.class);
        refreshView(students);
    }

    /**
     * 搜索所有的女生
     *
     * @param view
     */
    @OnClick(R.id.btn_query_girl)
    public void queryAllGirls(View view) {
        List<Student> students = LitePal.where("sex like 0").find(Student.class);
        refreshView(students);
    }

    /**
     * 搜索所有的男生
     *
     * @param view
     */
    @OnClick(R.id.btn_query_boy)
    public void queryAllBoys(View view) {
        List<Student> students = LitePal.where("sex like 1").find(Student.class);
        refreshView(students);
    }

    /**
     * 搜索所有的教师
     *
     * @param view
     */
    @OnClick(R.id.btn_quert_all_teachers)
    public void queryAllTeachers(View view) {
        List<Teacher> teachers = LitePal.findAll(Teacher.class);
        refreshView(teachers);
    }

    /**
     * 搜索Jack的学生
     *
     * @param view
     */
    @OnClick(R.id.btn_query_jack_students)
    public void queryJackStudents(View view) {
        Teacher teacher = LitePal.findFirst(Teacher.class, true);
        List<Student> students = teacher.getStudents();
        refreshView(students);
    }

    /**
     * 搜索Tom的学生
     *
     * @param view
     */
    @OnClick(R.id.btn_query_tom_students)
    public void queryTomStudents(View view) {
        Teacher teacher = LitePal.find(Teacher.class, 2, true);
        List<Student> students = teacher.getStudents();
        refreshView(students);
    }

    /**
     * 搜索Sam的学生
     *
     * @param view
     */
    @OnClick(R.id.btn_query_sam_students)
    public void querySamStudents(View view) {
        Teacher teacher = LitePal.findLast(Teacher.class, true);
        List<Student> students = teacher.getStudents();
        refreshView(students);
    }

    /**
     * 刷新并显示数据
     *
     * @param people
     */
    private void refreshView(List<? extends Person> people) {
        // 数据刷新必须使用同一个List，
        // 不能使用listA = listB进行赋值，该赋值方式会改变内存中的存储位置到listB,
        // 必须使用list.addAll()或者list.add()等来改变数据
        // 清除旧的数据
        mQueryResult.clear();
        // 加载新数据
        mQueryResult.addAll(people);
        // 刷新视图
        mResultAdapter.notifyDataSetChanged();
    }
}
